import axios from 'axios'
import { useLoadingStore } from '@src/stores/modules/loading'
const loadingStore = useLoadingStore()
const httpClient = axios.create({
  timeout: 50000
})

// 拦截请求
httpClient.interceptors.request.use(
  (config) => {
    // 请求前拦截, 例如添加token
    // todo
    loadingStore.startLoading()
    return config
  },
  (error) => {
    loadingStore.cancelLoading()
    // todo
    return Promise.reject(error)
  }
)

// 拦截响应
httpClient.interceptors.response.use(
  (response) => {
    loadingStore.cancelLoading()
    if (response.status == 200) {
      return {
        code: 1,
        rows: response.data
      }
    }
    // 响应拦截, 例如返回统一格式数据
    return response
  },
  (error) => {
    loadingStore.cancelLoading()
    return {
        code: -1,
        msg: error
    }
  }
)

export default httpClient